package com.xiaotao.consumer;

import com.xiaotao.util.WsUserSession;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import javax.annotation.Resource;

@Component
public class WsConnectListener implements ApplicationListener<ApplicationEvent> {

    @Resource
    private WsUserSession registry;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        if (event instanceof SessionConnectEvent) {
            SessionConnectEvent connectEvent = (SessionConnectEvent) event;
            String userId = (String) connectEvent.getMessage().getHeaders().get("user-id");
            String sessionId = (String) connectEvent.getMessage().getHeaders().get("simpSessionId"
            );

            if (userId != null) {
                registry.add(userId, sessionId);
                System.out.println(" WebSocket 连接成功: userId = " + userId + ", sessionId = " + sessionId);
            }
        }

        if (event instanceof SessionDisconnectEvent) {
            SessionDisconnectEvent disconnectEvent = (SessionDisconnectEvent) event;
            String sessionId = (String) disconnectEvent.getMessage().getHeaders().get("simpSessionId");
            registry.remove(sessionId);
            System.out.println("WebSocket 断开: sessionId = " + sessionId);
        }
    }
}
